package com.ecommerce.controller;

import com.alibaba.fastjson.JSON;
import com.ecommerce.annotation.IgnoreResponseAdvice;
import com.ecommerce.servie.JWTService;
import com.ecommerce.vo.JwtToken;
import com.ecommerce.vo.UsernameAndPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 对外暴露的授权服务接口
 */
@Slf4j
@RestController
@RequestMapping("/authority")
public class AuthorityController {

    private final JWTService jwtService;

    public AuthorityController(JWTService jwtService) {
        this.jwtService = jwtService;
    }

    /**
     * 从授权中心获取token(登录), 且返回信息中没有统一响应的包装
     */
    @IgnoreResponseAdvice
    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public JwtToken token(@RequestBody UsernameAndPassword usernameAndPassword) throws Exception{

        // 授权服务器不对外开放，可以打印密码
        log.info("request to get token with param: [{}]", JSON.toJSONString(usernameAndPassword));

        return new JwtToken(jwtService.generateToken(
                usernameAndPassword.getUsername(),
                usernameAndPassword.getPassword()
        ));
    }

    /**
     * 注册用户, 并返回当前注册用户的Token, 即通过授权中心创建用户
     */
    @IgnoreResponseAdvice
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public JwtToken register(@RequestBody UsernameAndPassword usernameAndPassword) throws Exception {
        log.info("register user with param: [{}]", JSON.toJSONString(
                usernameAndPassword
        ));
        return new JwtToken(jwtService.registerUserAndGenerateToken(
                usernameAndPassword
        ));
    }
}
